package com.copa.l234;

/**
 * @author copa
 * @createDate 2022-05-31 09:10
 * @function 快慢指针
 */
public class Test4 {

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            // 若head为空或者只有一个元素，直接返回true
            return true;
        }
        // 慢指针
        ListNode slow = head;
        // 快指针
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            // 若fast没到尽头，则要走，fast每次走两步，slow每次走一步
            slow = slow.next;
            fast = fast.next.next;
        }
        if (fast == null) {
            // 如果fast走到null，证明head为偶数，slow正好到回文数的第一个位置，然后开始反转链表
            slow = reverseListNode(slow);
        } else {
            // 如果fast没有走到null，证明head为奇数，slow正好到head的中间位置，则需要再走一般再开始反转链表
            slow = reverseListNode(slow.next);
        }
        // 然后把fast跳到head的位置
        fast = head;
        while (slow != null) {
            // 此时fast跟slow指向的数进行一一比对，两个指针都每次走一步
            if (fast.val != slow.val) {
                return false;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }

    /**
     * 反转链表，具体解释可以看l206
     * @param slow
     * @return
     */
    private ListNode reverseListNode(ListNode slow) {
        if (slow.next == null) {
            return slow;
        }
        ListNode node = reverseListNode(slow.next);
        slow.next.next = slow;
        slow.next = null;
        return node;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(1);
//        head.next.next.next.next = new ListNode(1);
        System.out.println(new Test4().isPalindrome(head));
    }
}
